/**
 * @author DongPing
 * 2022/1/12 9:54
 *
 * 收款池-业务认领 认领明细
 *
 * */
import {useCallback, useContext, useEffect, useRef, useState} from "react";
import {getAllTypesOfMetasByPageCode} from "@/biz-components/claim-items/components/meta-model-utilities";
//import {AssetCard} from "@/biz-components/claim-items/collection-business/AssetCard";
//import {AdjustmentOrder} from "@/biz-components/claim-items/collection-business/AdjustmentOrder";
import {DetailContext} from "@/biz-components/claim-items/components/DetailContext";
import {AsyncPageSelectSearchParam, ValidateStyleAdjustment} from "@/biz-components/claim-items/components";
import {xhrPostJson} from "@/services";
import {useField} from "@formily/react";
import {Field} from "@formily/core/lib/models";
import {CellInput, CommonFilter, CommonFilterItem, FilterFunctions} from "@/biz-components/claim-items/components-v2";
import * as CommonDataSource from "@/common-data-source";
import {
  AsyncPageMultipleSelectExtraProps,
  SelectorExtraProps
} from "@/biz-components/claim-items/components-v2/cell-input";
import {CommonTable} from "@/biz-components/claim-items/components-v2/CommonTable";
import ClaimItemsDataUtil from "@/biz-components/claim-items/ClaimItemsDataUtil";
import {minus, plus} from "@ey-utils/utils/numberPrecision";

// 表格数据的子模型编码
const PageCode = 'ClaimInfoA_IT_L';

/**
 * 认领明细表格里面的业务单据类型
 * @TODO 类型的值待确认
 * */
// enum BUSINESS_ORDER_TYPE {
// 	// OA的资产废品出售
// 	OA_SALE = 'oas',
// 	// OA的现金存缴单
// 	OA_CASH = 'oac'
// }
// // 认领明细表格的业务单据类型这个字段的名称
// const BUSINESS_ORDER_TYPE_ATTRIBUTE_NAME = 'bizDocType';
//
// // 表格数据里面的资产卡片属性名称（用于取值）@TODO
// const ASSET_CARD_ATTRIBUTE_NAME = 'unconfirmed_1';
// // 表格数据里面的差异调整单属性名称（用于取值）@TODO
// const DIFFER_ADJUSTMENT_ATTRIBUTE_NAME = 'unconfirmed_2';

export function CollectionBusiness(props: {
	// 认领门店编码， 用于查询员工和柜组的选择项
	shopCode: string,
	// 认领对象
	claimTarget: string,
	// 匹配性质
	matchType: string,

	value: any[],
	onChange: (value: any[]) => void,

}) {

	const {value= [], onChange, shopCode, claimTarget, matchType} = props;

	const [tableColumnMetas, setTableColumnMetas] = useState<any[]>([]);
	useEffect(function () {
		getAllTypesOfMetasByPageCode(PageCode).then((result) => {
			setTableColumnMetas(result.tableColumnMetas);
		})
	}, []);

	/**
	 * 记录上一次查询的数据
	 * */
	const lastDataRef = useRef<any[]>(null);

	/**
	 * 过滤器过滤数据的方法
	 * */
	const filterFunctionRef = useRef<((data: any[]) => any[]) | null>(null);
	/**
	 * 过滤器数据变化，或者重新查询了数据
	 * */
	const onFilterOrDataChange = useCallback(() => {
		if(!lastDataRef.current) return;
		if(filterFunctionRef.current) {
			props.onChange(filterFunctionRef.current(lastDataRef.current));
		}
	}, [filterFunctionRef, lastDataRef]);


	const detailMode = useContext(DetailContext);
	// 根据认领门店和认领对象查询认领明细数据
	useEffect(function () {
		if(detailMode ) return;
		if(!shopCode) {
			return;
		}

		xhrPostJson('/asm/claimDetail/bizCllctList', {
			companyCode: shopCode,
			matchNatur: matchType,
			claimObject: claimTarget
		})
			.then((res: any) => {
				// @ts-ignore
				lastDataRef.current = res.result || [];
				onFilterOrDataChange();
			})
	}, [shopCode, claimTarget, matchType]);



	const validateTableDataRef = useRef(() => true);

	const field = useField<Field>();
	useEffect(function () {
		field.setValidator(() => {
			if(!value.some((item) => item.__checked)) {
				return {type: 'error', message: '请选择认领明细'}
			}
			return validateTableDataRef.current() ? null : {type: 'error', message: '本次认领金额不能大于未认领金额'};
		});
		return function () {
			field.setValidator(() => true);
		}
	}, [value]);

	const queryEmployeeCallback = useCallback((p: AsyncPageSelectSearchParam) => {
		return CommonDataSource.shop.queryShopEmployees(p, props.shopCode)
	}, [props.shopCode]);
	const querySaleBarCallback = useCallback((p: AsyncPageSelectSearchParam) => {
		return CommonDataSource.shop.querySAPShopDepartmentsPage(p, props.shopCode);
	}, [props.shopCode]);

	const [detailOptions, setDetailOptions] = useState<Array<{name: string, value: string}>>([]);
	useEffect(function () {
		CommonDataSource?.dictionary?.queryAllChildren?.({dictType: 'BANK_PYMT_BIZ_TYPE'})
			.then(setDetailOptions);
	}, []);

	const sourceSystemOptions = CommonDataSource.dictionary.useDictionaryOptions('SOURCE_SYSTEM');


	function onCheckChange(record: object | null, checked: boolean) {
		for(const item of value) {
			if(
				(item === record)
				||
				(null === record)
			) {
				item.__checked = checked;
				if(checked) {
					/**
					 * http://jira.ecsphere.net:9080/browse/XYL-1733
					 * 涉及资金的业务单据认领方式，勾选对应的业务单据后，本次认领金额默认取单据金额，不可编辑
					 * */
					if(((item.cllctDetail === 'DKDZ01') && (item.bizDetailType === 'D03')) || item.cllctDetail === 'SBX01') {
						item.thisClaimAmt = item.billAmt;
					} else {
						item.thisClaimAmt = item.unClaimedAmt;
					}
				} else {
					item.thisClaimAmt = '';
				}
			} else {

			}
		}
		props.onChange([...value]);
	}

	return (
		<>
			{
				detailMode ? null :
					<ValidateStyleAdjustment invalid={false}>
						<CommonFilter filterFunctionRef={filterFunctionRef} onChange={onFilterOrDataChange} metaArr={tableColumnMetas}>
							<CommonFilterItem name={'bizCode'} Component={[CellInput.TextInput, {}]} filterFunction={FilterFunctions.stringLike}/>
							<CommonFilterItem name={'applyDate'} Component={[CellInput.SelectDateRange, {}]} filterFunction={FilterFunctions.dateRangeMatch}/>
							<CommonFilterItem<string[], AsyncPageMultipleSelectExtraProps> name={'employeeId'} Component={[CellInput.AsyncPageMultipleSelect, {search: queryEmployeeCallback}]} filterFunction={FilterFunctions.stringArrayIncludes}/>
							<CommonFilterItem<string[], AsyncPageMultipleSelectExtraProps> name={'branchDeptCode'} Component={[CellInput.AsyncPageMultipleSelect, {search: querySaleBarCallback}]} filterFunction={FilterFunctions.stringArrayIncludes}/>
							<CommonFilterItem<string, SelectorExtraProps> name={'cllctDetail'} Component={[CellInput.Selector, {dataSource: detailOptions, showSearch: true}]} filterFunction={FilterFunctions.stringEqual}/>
							<CommonFilterItem<any, {}> name={'billAmt'} Component={[CellInput.NumberInput, {}]} filterFunction={FilterFunctions.numberEqual}/>
							<CommonFilterItem<any, CellInput.SelectorExtraProps> name={'sourceSystem'} Component={[CellInput.Selector, {dataSource: sourceSystemOptions}]} filterFunction={FilterFunctions.stringEqual}/>
						</CommonFilter>
					</ValidateStyleAdjustment>

			}

			<CommonTable
				pageCode={PageCode}
				metaArr={tableColumnMetas}
				value={value}
				onChange={onChange}
				detailMode={detailMode}
				claimItemsInvalid={true}
				validateFunctionRef={validateTableDataRef}
				columnsOptionArr={[
					{
						name: 'thisClaimAmt',
						component: [CellInput.NumberInput, {}],
						validator: (v, record) => {
							if(!record.__checked) return true;
							let nThis = Number(record.thisClaimAmt);
							if(isNaN(nThis)) return false;
							if(nThis <= 0) return false;
							return nThis <= Number(record.unClaimedAmt)
						},
						/*
						 * http://jira.ecsphere.net:9080/browse/XYL-1733
						 * */
						disabled: (record: any) => {
						  if (record.cllctDetail === 'SBX01') {
						    return true;
              }
							return (record.cllctDetail === 'DKDZ01') && (record.bizDetailType === 'D03')
						}
					},
					{
						name: 'employeeId',
						hide: matchType === 'Personnel'
					},
					{
						name: 'employeeName',
						hide: matchType === 'Personnel'
					}
				]}
				// renderOptions={(r: any) => {
				// 	return (
				// 		<div>
				// 			{
				// 				r[BUSINESS_ORDER_TYPE_ATTRIBUTE_NAME] === BUSINESS_ORDER_TYPE.OA_SALE ? <AssetCard data={r[ASSET_CARD_ATTRIBUTE_NAME]}/> : null
				// 			}
				// 			{
				// 				r[BUSINESS_ORDER_TYPE_ATTRIBUTE_NAME] === BUSINESS_ORDER_TYPE.OA_CASH ? <AdjustmentOrder data={r[DIFFER_ADJUSTMENT_ATTRIBUTE_NAME]}/> : null
				// 			}
				// 		</div>
				// 	)
				// }}
				checkOperation
				onCheckChange={onCheckChange}
			/>
		</>

	)
}
/**
 *
 * http://jira.ecsphere.net:9080/browse/XYL-1351
 *
 * bizType=“SAP_XJCJD”的时候，认领总金额的计算逻辑：
 *认领总金额=（Z01-Z03-Z05+Z04）对应勾选的本次认领金额汇总（bizDetailedType取值：Z01-Z03-Z05+Z04）
 *
 * */
CollectionBusiness.calcTotalAmt = function (data: any[]) {
	let total = 0;
	for(const item of data) {
		if(item.__checked) {
			total = (
						(
							(item.bizType === 'SAP_XJCJD') && ['Z03', 'Z05'].includes(item.bizDetailType)
						)
						?
						minus
						:
						plus
			)(total, toNumber(item.thisClaimAmt))
		}
	}
	return total;
}

/**
 * 将一个值转化为number，如果不能转为number 返回0
 * */
function toNumber(source: any) {
	let n = Number(source);
	return isNaN(n) ? 0 : n;
}

CollectionBusiness.getCheckedValues = function (data: any[] = []) {
	return ClaimItemsDataUtil.removeTempId(data.filter((item) => {
		let valid = item.__checked === true;
		delete item.__checked;
		return valid;
	}))
}

